﻿//  Copyright (c) 2010 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DNA.Mvc.Publishing;

namespace DNA.Mvc.Publishing.Controllers
{
    public class LibraryController : Controller
    {
        private IPubContext pubContext;
        private readonly string baseImageUrl = "~/content/images/";
        
        private string ResolveUrl(string filename)
        {
            return Url.Content(baseImageUrl + filename);
        }

        private string ResolveUrl(Category cat)
        {
            return !string.IsNullOrEmpty(cat.Url) ? Url.Content(cat.Url) : Url.Content("~/publishing/library/c/" + cat.ID.ToString() + ".html");
        }

        private string ResolveUrl(Article article)
        {
            return Url.Content("~/publishing/library/t/" + article.ID.ToString() + ".html");
        }

        public LibraryController(IPubContext context)
        {
            pubContext = context;
        }

        public ActionResult Index()
        {
            return View(pubContext.Categories.Find(WebSiteContext.Current.Web.Name));
        }

        public ActionResult GetNodes(int id)
        {
            Category category = null;
            if (id == 0)
            {
                category = pubContext.Categories.Find(WebSiteContext.Current.Web.Name);
            }
            else
                category = pubContext.Categories.Find(id);

            var childrenCats = pubContext.Categories.Children(category.ID);  
            var childrenArts =category.Articles.OrderBy(a => a.Pos);
            var nodes = new List<SelectableNode>();
            foreach (var cat in childrenCats)
            {
                nodes.Add(new SelectableNode()
                {
                    Title = cat.Title,
                    ImageUrl = ResolveUrl("icon_dir_16.gif"),
                    NavigateUrl =ResolveUrl(cat),
                    Target = "contentWindow",
                    Value = Url.Action("GetNodes", new { Area = "Publishing", id = cat.ID }),
                    Properties=0
                });
            }

            foreach (var art in childrenArts)
            {
                if (art.ParentID > 0)
                    continue;

                if ((art.IsPrivate) || (!art.IsPublished))
                {
                    if (!HttpContext.Request.IsAuthenticated)
                        continue;
                    if (!art.UserName.Equals(User.Identity.Name, StringComparison.OrdinalIgnoreCase))
                        continue;
                }
                
                bool hasChildren = pubContext.Articles.HasChildren(art.ID);

                var node = new SelectableNode()
                {
                    Title = art.Title,
                    Target = "contentWindow",
                    ImageUrl = art.IsPrivate ? ResolveUrl("doc_private.gif") : (art.IsPublished ? (hasChildren ? ResolveUrl("posts.gif") : ResolveUrl("doc_content.gif")) :ResolveUrl("doc_draft.gif")),
                    NavigateUrl =ResolveUrl(art),
                    Properties=art.ID
                };

                if (hasChildren)
                    node.Value = Url.Action("GetArticleNodes", new { Area = "Publishing", id = art.ID });
                else
                    node.Value = null;
                nodes.Add(node);
            }
            /*For json convertion*/
            var jsonNodes = from n in nodes
                            select new
                            {
                                title = n.Title,
                                url = n.NavigateUrl,
                                imgUrl = n.ImageUrl,
                                hasChildren = n.Value != null,
                                rel = n.Value as string,
                                id=(int)n.Properties
                            };

            return Json(jsonNodes.ToList(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetArticleNodes(int id)
        {
           // var web = WebSite.Open();
            //var article = pubContext.Articles.Find(id);
            
            // web.FindArticle(id);
            var childrenArts = pubContext.Articles.GetChildren(id);
            // article.GetChildren();
            var nodes = new List<SelectableNode>();

            foreach (var art in childrenArts)
            {
                if ((art.IsPrivate) || (!art.IsPublished))
                {
                    if (!HttpContext.Request.IsAuthenticated)
                        continue;
                    if (!art.UserName.Equals(User.Identity.Name, StringComparison.OrdinalIgnoreCase))
                        continue;
                }

                bool hasChildren=pubContext.Articles.HasChildren(art.ID);
                var node = new SelectableNode()
                {
                    Title = art.Title,
                    Target = "contentWindow",
                    ImageUrl = art.IsPrivate ? ResolveUrl("doc_private.gif") : (art.IsPublished ? (hasChildren ? ResolveUrl("posts.gif") : ResolveUrl("doc_content.gif")) : ResolveUrl("doc_draft.gif")),
                    NavigateUrl =ResolveUrl(art),
                    Properties=art.ID
                };

                if (hasChildren)
                //if (art.HasChildren())
                    node.Value = Url.Action("GetArticleNodes", new { Area = "Publishing", id = art.ID });
                else
                    node.Value = null;

                nodes.Add(node);
            }
            var jsonNodes = from n in nodes
                            select new
                            {
                                title = n.Title,
                                url = n.NavigateUrl,
                                imgUrl = n.ImageUrl,
                                hasChildren = n.Value != null,
                                rel = n.Value as string,
                                id=(int)n.Properties
                            };
            return Json(jsonNodes.ToList(), JsonRequestBehavior.AllowGet);
        }

       // [Log]
        public ActionResult ContentsTable(int id)
        {
            return View(pubContext.Categories.Find(id));
        }

        //[Log]
        public ActionResult Topic(int id)
        {
            var article = pubContext.Articles.Find(id);
            if (article != null)
            {
                if (article.IsPublished)
                    pubContext.Articles.Read(id, User.Identity.Name, Request.UserHostAddress, Request.UserAgent);
                return View(article);
            }
            else
                return HttpNotFound();
            throw new HttpException(404, "Page not found.");
        }
    }
}
